package com.shengdong.water.code.base

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView


abstract class BaseRecyclerAdapter<T, VB : ViewDataBinding> :
    RecyclerView.Adapter<BaseRecyclerAdapter.BaseViewHolder<VB>>() {

    // 数据列表
    private val items = mutableListOf<T>()

    // 点击事件监听器
    private var itemClickListener: ((T, Int) -> Unit)? = null

    // 获取布局ID的抽象方法
    abstract fun getLayoutId(): Int

    // 绑定数据的方法，可以在子类中重写
    open fun bindData(binding: VB, item: T, position: Int) {
    }

    // 设置点击事件监听器
    fun setOnItemClickListener(listener: (T, Int) -> Unit) {
        this.itemClickListener = listener
    }

    // 更新数据列表
    fun setItems(newItems: List<T>) {
        val diffCallback = object : DiffUtil.Callback() {
            override fun getOldListSize() = items.size
            override fun getNewListSize() = newItems.size

            override fun areItemsTheSame(oldPos: Int, newPos: Int): Boolean {
                return areItemsTheSame(items[oldPos], newItems[newPos])
            }

            override fun areContentsTheSame(oldPos: Int, newPos: Int): Boolean {
                return areContentsTheSame(items[oldPos], newItems[newPos])
            }
        }

        val diffResult = DiffUtil.calculateDiff(diffCallback)
        items.clear()
        items.addAll(newItems)
        diffResult.dispatchUpdatesTo(this)
    }

    // 判断两个item是否是同一个，默认实现，子类可重写
    open fun areItemsTheSame(oldItem: T, newItem: T): Boolean {
        return oldItem == newItem
    }

    // 判断两个item内容是否相同，默认实现，子类可重写
    open fun areContentsTheSame(oldItem: T, newItem: T): Boolean {
        return oldItem == newItem
    }

    // 获取指定位置的数据
    fun getItem(position: Int): T = items[position]

    // 获取当前数据列表
    fun getItems(): List<T> = items

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder<VB> {
        val binding = DataBindingUtil.inflate<VB>(
            LayoutInflater.from(parent.context),
            getLayoutId(),
            parent,
            false
        )
        return BaseViewHolder(binding)
    }

    override fun onBindViewHolder(holder: BaseViewHolder<VB>, position: Int) {
        val item = items[position]
        bindData(holder.binding, item, position)

        // 设置点击事件
        holder.binding.root.setOnClickListener {
            itemClickListener?.invoke(item, position)
        }

        // 确保绑定会立即执行
        holder.binding.executePendingBindings()
    }

    override fun getItemCount(): Int = items.size

    // ViewHolder基类
    class BaseViewHolder<VB : ViewDataBinding>(val binding: VB) :
        RecyclerView.ViewHolder(binding.root)



    /**
     * 数据是否为空
     */

    fun isEmpty(): Boolean = items.isEmpty()


    /**
     * 添加单个数据项
     */

    fun addItem(item: T) {

        items.add(item)

        notifyItemInserted(items.size - 1)

    }

    /**
     * 添加数据列表
     */

    fun addItems(newItems: List<T>) {

        val startPosition = items.size

        items.addAll(newItems)

        notifyItemRangeInserted(startPosition, newItems.size)

    }

    /**
     * 清空数据
     */
    @SuppressLint("NotifyDataSetChanged")
    fun clearItems() {
        items.clear()
        notifyDataSetChanged()

    }

    /**
     * 移除指定位置的数据
     */
    fun removeItem(position: Int) {

        if (position >= 0 && position < items.size) {

            items.removeAt(position)

            notifyItemRemoved(position)

        }
    }

    /**
     * 移除指定数据项
     */
    fun removeItem(item: T) {

        val position = items.indexOf(item)

        if (position >= 0) {

            removeItem(position)

        }

    }
}